package com.dreamer.view.lottery;

import com.dreamer.domain.lottery.Lottery;
import com.dreamer.domain.lottery.vo.UserVo;
import com.dreamer.domain.user.User;
import com.dreamer.service.lottery.LotteryHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import ps.mx.otter.utils.SearchParameter;
import ps.mx.otter.utils.WebUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/lottery")
public class LotteryQueryController {

    @Autowired
    private LotteryHandler lotteryHandler;

//    @RequestMapping("/index.html")
//    public String index(
//            @ModelAttribute("parameter") SearchParameter<Lottery> parameter,
//            HttpServletRequest request, Model model) {
//        try {
//            List<Lottery> list = lotteryHandler.searchAllByPage(parameter);
//            WebUtil.turnPage(parameter, request);
//            model.addAttribute("lotteryList", list);
//        } catch (Exception exp) {
//            exp.printStackTrace();
//        }
//        return "lottery/lottery_index";
//    }

    @RequestMapping("/index.html")
    public String index(Model model) {
        try {
            List list = lotteryHandler.findLotteryVoAll();
            model.addAttribute("lotteryList", list);
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return "lottery/lottery_index";
    }

    @RequestMapping(value = "/edit.html", method = RequestMethod.GET)
    public String edit_enter(@ModelAttribute("parameter") SearchParameter<Lottery> parameter, HttpServletRequest request) {
        User user = (User) WebUtil.getCurrentUser(request);
        if (user.isAdmin()) {
            return "lottery/activity_edit";
        } else {
            return "common/403";
        }

    }

    @ModelAttribute("parameter")
    public SearchParameter<Lottery> preprocess(@RequestParam("id") Optional<Integer> id) {
        SearchParameter<Lottery> parameter = new SearchParameter<>();
        Lottery  lottery;
        if (id.isPresent()) {
            lottery = lotteryHandler.findById(id.get());
        }else {
            lottery=new Lottery();
        }
        parameter.setEntity(lottery);
        return parameter;
    }

}
